﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Web.Core;
using System.Collections;

namespace Yuanlin.Business
{
    public class ZiCaiInfoEditControl : YuanlinUserControl,
        IReplyConverter<ZiCaiInfoReply, GetOperation>
    {
        protected ValuedTextBox titleValuedTextBox;
        protected ValuedTextBox priceValuedTextBox;
        protected ValuedEditor descriptionValuedEditor;
        protected ValuedDropDownList topZiCaiCategoryDropDownList;
        protected ValuedDropDownList secondZiCaiCategoryDropDownList;
        protected RadioButtonList categoryRadioButtonList;//分类
        protected HiddenField specificationHiddenField;
        protected ValuedTextBox registerTrademarkValuedTextBox;
        protected HtmlImage viewImage;
        protected HtmlInputFile attachmentData;
        protected Literal zicaiInfoLiteral;
        protected IButton SaveButton;
        protected IButton BackButton;
        private ZiCaiInfo ziCaiInfo = null;
        private int kind = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.Kind);
        private string tradeType = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.TradeType);

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetZiCaiInfoRequest(this));
        }
        protected override void OnLoad(EventArgs e)
        {
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
            AjaxManager.Register(this, "AjaxMethod");
        }

        private void Bind()
        {
            zicaiInfoLiteral.Text = ZiCaiInfoControl.TitleStr(kind, tradeType);

            if (ziCaiInfo == null)
            {
                return;
            }
            viewImage.Src = SiteUrls.Instance().GetAttachmentFullVirtualPathUrl(ziCaiInfo);
            viewImage.Attributes.Add("onclick", "javascript:window.open('" + viewImage.Src + "')");
            viewImage.Alt = ziCaiInfo.Title.Value;
            this.titleValuedTextBox.Value = ziCaiInfo.Title.Value;
            this.descriptionValuedEditor.Value = ziCaiInfo.Body.Value;
            priceValuedTextBox.Value = ziCaiInfo.Price.Value.ToString("f2");
            registerTrademarkValuedTextBox.Text = ziCaiInfo.RegisterTrademark.Value;

            ZiCaiListRequest request = new ZiCaiListRequest();
            request.UpZiCaiId = 0;
            EntityList topCategories = BusinessManager.GetZiCaiList(RequestHelper.BuildGetZiCaiListRequest(request));

            topZiCaiCategoryDropDownList.DataSource = topCategories;
            topZiCaiCategoryDropDownList.DataValueField = "EntityId";
            topZiCaiCategoryDropDownList.DataTextField = "Title";
            topZiCaiCategoryDropDownList.DataBind();
            topZiCaiCategoryDropDownList.Value = ziCaiInfo.TopCategory.Value.ToString();

            ZiCaiListRequest request1 = new ZiCaiListRequest();
            request1.UpZiCaiId = Convert.ToInt32(ziCaiInfo.TopCategory.Value);
            EntityList secondCategorys = BusinessManager.GetZiCaiList(RequestHelper.BuildGetZiCaiListRequest(request1));

            secondZiCaiCategoryDropDownList.DataSource = secondCategorys;
            secondZiCaiCategoryDropDownList.DataValueField = "EntityId";
            secondZiCaiCategoryDropDownList.DataTextField = "Title";
            secondZiCaiCategoryDropDownList.DataBind();
            secondZiCaiCategoryDropDownList.Value = ziCaiInfo.SecondCategory.Value.ToString();

            //资材规格分类
            ZiCaiGuiGeCategoryListRequest request2 = new ZiCaiGuiGeCategoryListRequest();
            request2.ZiCaiId = kind;
            request2.PageIndex = 0;
            request2.PageSize = 10000;
            EntityList categories = BusinessManager.GetZiCaiGuiGeCategoryList(RequestHelper.BuildGetZiCaiGuiGeCategoryListRequest(request2));

            this.categoryRadioButtonList.DataSource = categories;
            this.categoryRadioButtonList.DataTextField = "Title";
            this.categoryRadioButtonList.DataValueField = "EntityId";
            this.categoryRadioButtonList.DataBind();
            categoryRadioButtonList.SelectedValue = ziCaiInfo.CategoryId.Value.ToString();

            if (ziCaiInfo.CategoryId.Value > -1)
            {
                BindUnit();
            }

        }
        private void BindUnit()
        {
            string returnValue = string.Empty;
            if (string.IsNullOrEmpty(ziCaiInfo.GuiGeNames.Value) || string.IsNullOrEmpty(ziCaiInfo.GuiGeValues.Value))
            {
                return;
            }
            string[] names = ziCaiInfo.GuiGeNames.Value.Split(new string[] { "|" }, StringSplitOptions.None);
            string[] values = ziCaiInfo.GuiGeValues.Value.Split(new string[] { "|" }, StringSplitOptions.None);
            string[] units = ziCaiInfo.GuiGeUnits.Value.Split(new string[] { "|" }, StringSplitOptions.None);

            if (names.Length != values.Length)
            {
                return;
            }
            for (int i = 0; i < names.Length; i++)
            {
                returnValue += ";" + string.Format("{0}:{1}:{2}", names[i], units[i], values[i]);
            }
            if (returnValue.Length > 0)
            {
                returnValue = returnValue.Substring(1);
            }
            //绑定规格
            specificationHiddenField.Value = returnValue;

        }

        public void BackButton_Click(object sender, EventArgs e)
        {
            RedirectUrl();
        }
        private void RedirectUrl()
        {
            if (kind == 1)//机械
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyMachineChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyMachineQiuGouListUrl());
                }
            }
            else if (kind == 2)//设施
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyFacilityChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyFacilityQiuGouListUrl());
                }
            }
            else if (kind == 3)//农资
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyAgriculturalChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyAgriculturalQiuGouListUrl());
                }
            }
            else if (kind == 4)//化肥
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyHuaFeiChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyHuaFeiQiuGouListUrl());
                }
            }
            else if (kind == 5)//饲料
            {
                if (tradeType == "0")//出售
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyMashChuShouListUrl());
                }
                else if (tradeType == "1")//求购
                {
                    Page.Response.Redirect(SiteUrls.Instance().GetCompanyMashQiuGouListUrl());
                }
            }
        }
        public void SaveButton_Click(object sender, EventArgs e)
        {
            ziCaiInfo.Title.Value =  CensorWordManager.CensorWord(this.titleValuedTextBox.Value);
            ziCaiInfo.Body.Value =  CensorWordManager.CensorWord(this.descriptionValuedEditor.Value);
            ziCaiInfo.TradeType.Value = tradeType;
            ziCaiInfo.TopCategory.Value = int.Parse(topZiCaiCategoryDropDownList.Value);
            ziCaiInfo.SecondCategory.Value = int.Parse(Page.Request.Form[this.secondZiCaiCategoryDropDownList.UniqueID]);
            ziCaiInfo.Kind.Value = kind;
            ziCaiInfo.Price.Value = priceValuedTextBox.Value.Length == 0 ? 0 : (float)(Convert.ToDecimal(priceValuedTextBox.Text));
            ziCaiInfo.RegisterTrademark.Value = registerTrademarkValuedTextBox.Text.Trim();
            ziCaiInfo.CategoryId.Value = Int32.Parse(categoryRadioButtonList.SelectedValue);
            string topCategoryText = string.Empty;
            string secondCategoryText = string.Empty;

            ZiCai topZiCai = BusinessManager.GetZiCai(ziCaiInfo.TopCategory.Value);
            if (topZiCai != null)
            {
                topCategoryText = topZiCai.Title.Value;
            }
            ZiCai secondZiCai = BusinessManager.GetZiCai(ziCaiInfo.SecondCategory.Value);
            if (secondZiCai != null)
            {
                secondCategoryText = secondZiCai.Title.Value;
            }
            ziCaiInfo.SecondCategoryText.Value = secondCategoryText;
            ziCaiInfo.CategoryInfo.Value = string.Format("{0}/{1}", topCategoryText, secondCategoryText);
            ziCaiInfo.UpdateDate.Value = DateTime.Now;

            List<string> fieldNames = new List<string>();
            List<string> fieldValues = new List<string>();
            List<string> fieldUnits = new List<string>();
            if (specificationHiddenField.Value.Length > 0)
            {
                string[] specifications = specificationHiddenField.Value.Split(';');
                foreach (string item in specifications)
                {
                    fieldNames.Add(item.Split(':')[0]);
                    fieldValues.Add(item.Split(':')[1]);
                    fieldUnits.Add(item.Split(':')[2]);
                }
            }
            ziCaiInfo.GuiGeNames.Value = string.Join("|", fieldNames.ToArray());
            ziCaiInfo.GuiGeValues.Value = string.Join("|", fieldValues.ToArray());
            ziCaiInfo.GuiGeUnits.Value = string.Join("|", fieldUnits.ToArray());

            BusinessManager.UpdateZiCaiInfo(ziCaiInfo);

            if (SiteUrls.Instance().IsAttachmentValid(attachmentData))
            {
                SiteUrls.Instance().DeleteFile(SiteUrls.Instance().GetFile(ziCaiInfo));
                ziCaiInfo.AttachmentFileName.Value = SiteUrls.Instance().GetPostedFileName(attachmentData);
                BusinessManager.UpdateZiCaiInfo(ziCaiInfo);
                SiteUrls.Instance().SaveFile(SiteUrls.Instance().GetFile(ziCaiInfo), attachmentData);
            }

            RedirectUrl();
        }

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string GetChildCategories(int parentCategoryID)
        {
            if (parentCategoryID == -1)
            {
                return string.Empty;
            }
            ZiCaiListRequest request = new ZiCaiListRequest();
            request.UpZiCaiId = parentCategoryID;
            EntityList categories = BusinessManager.GetZiCaiList(RequestHelper.BuildGetZiCaiListRequest(request));
            if (categories != null && categories.Count > 0)
            {
                string categoryFormat = "{0}:{1}";
                string categoryString = string.Empty;
                foreach (ZiCai category in categories)
                {
                    categoryString += ";" + string.Format(categoryFormat, category.EntityId.Value.ToString(), category.Title.Value);
                }
                if (categoryString.Length > 0)
                {
                    categoryString = categoryString.Substring(1);
                }
                return categoryString;
            }

            return string.Empty;
        }

        [AjaxMethod(IncludeControlValuesWithCallBack = false)]
        public string ParentCategorySelectedChanged(string selectedValue)
        {
            if (string.IsNullOrEmpty(selectedValue))
            {
                return "";
            }

            return BindGuiGes(int.Parse(selectedValue));
        }
        private string BindGuiGes(int categoryID)
        {
            string returnValue = string.Empty;
            if (categoryID < 0)
            {
                return returnValue;
            }

            //绑定规格
            ZiCaiGuiGeListRequest request = new ZiCaiGuiGeListRequest();
            request.CategoryId = categoryID;
            EntityList ziCaiGuiGes = BusinessManager.GetZiCaiGuiGeList(RequestHelper.BuildGetZiCaiGuiGeListRequest(request));
            if (ziCaiGuiGes.Count > 0)
            {
                string format = "{0}:{1}";
                string str = string.Empty;
                foreach (ZiCaiGuiGe item in ziCaiGuiGes)
                {
                    str += ";" + string.Format(format, item.Title.Value, item.Unit.Value);
                }
                if (str.Length > 0)
                {
                    str = str.Substring(1);
                }
                returnValue = str;
            }

            return returnValue;
        }

        #region IReplyConverter<ZiCaiInfoReply,GetOperation> Members

        public void ConvertReply(ZiCaiInfoReply reply, GetOperation operation)
        {
            if (reply != null)
            {
                ziCaiInfo = reply.Entity as ZiCaiInfo;

                if (!Page.IsPostBack)
                {
                    Bind();
                }
            }
        }

        #endregion
    }
}